import { login, userInfo, userProfile } from '../../api/user'
import { setToken, getToken, removeToken,getTimeStamp,setTimeStamp } from '../../utils/auth'
const state = {
  // 保存token
  token: getToken(),
  // 声明一个保存用户信息的state
  userInfo: {}
}
const mutations = {
  // 设置token
  setToken (state, token) {
    state.token = token
    setToken(token)
    setTimeStamp()
  },
  // 设置用户信息
  setUserInfo (state, payload) {
    state.userInfo = payload
  },
  // 删除token
  removeToken (state) {
    state.token = null
    // 删除本地的token
    removeToken()
  },
  // 删除用户信息
  removeUserInfo (state) {
    state.userInfo = {}
  }
}
const actions = {
  // 发请求获取token
  async login (context, data) {
    try {
      let res = await login(data)

      context.commit('setToken', res.data)
    } catch (error) {
      return Promise.reject(error)
    }
  },
  // 发请求获取用户信息
  async getUserInfo (context) {
    let res = await userInfo()
    // 发请求获取基本信息
    let res2 = await userProfile(res.data.userId)
    let allInfo = {
      ...res.data,
      ...res2.data
    }
    context.commit('setUserInfo', allInfo)
  },
  // 做退出
  logout (context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
